package p.ithorns.tools.translator.apt.creator;

import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import p.ithorns.tools.translator.apt.BaseProcessor;

/**
 * GetterCreator
 *
 * @author HtL
 * @date 2025/4/3 14:58
 * @since 1.0.0
 */
public class GetterCreator extends BaseMethodCreator {

    public GetterCreator(BaseProcessor processor) {
        super(processor);
    }

    public JCMethodDecl create(JCVariableDecl jcVariable) {
        Name varName = jcVariable.getName();
        //修改方法级别
        JCModifiers jcModifiers = treeMaker.Modifiers(Flags.PUBLIC);

        //添加方法名称
        Name methodName = makeCamelSignature(varName, "get");

        //添加方法内容
        ListBuffer<JCStatement> jcStatements = new ListBuffer<>();
        jcStatements.append(
                treeMaker.Return(treeMaker.Select(treeMaker.Ident(getNameFromString("this")), varName)));
        JCBlock jcBlock = treeMaker.Block(0, jcStatements.toList());

        //添加返回值类型
        JCExpression returnType = jcVariable.vartype;

        //参数类型
        List<JCTypeParameter> typeParameters = List.nil();

        //参数变量
        List<JCVariableDecl> parameters = List.nil();

        //声明异常
        List<JCExpression> throwsClauses = List.nil();
        //构建方法
        JCMethodDecl getter = treeMaker.MethodDef(jcModifiers, methodName, returnType, typeParameters, parameters, throwsClauses, jcBlock, null);
        processor.info("[GetterCreator]-> create Getter for field <{}>: ↲\r\n{}", varName, getter.toString());
        return getter;
    }

    private JCExpression memberAccess(String components) {
        String[] componentArray = components.split("\\.");
        JCExpression expr = treeMaker.Ident(getNameFromString(componentArray[0]));
        for (int i = 1; i < componentArray.length; i++) {
            expr = treeMaker.Select(expr, getNameFromString(componentArray[i]));
        }
        return expr;
    }

}